#!/usr/bin/python -B

from string import Template, upper, replace

from ApiUtil import outputCode
from ApiUtil import typeIsVoid

from ApiCodeGen import *

from RegalDispatchLog import apiDispatchFuncInitCode
from RegalDispatchEmu import dispatchSourceTemplate
from RegalContextInfo import cond

from RegalDispatchShared import dispatchSourceTemplate
from RegalDispatchShared import apiDispatchFuncInitCode
from RegalDispatchShared import apiDispatchGlobalFuncInitCode

from Emu       import emuFindEntry, emuCodeGen

##############################################################################################

def apiStatisticsFuncDefineCode(apis, args):
  categoryPrev = None
  code = ''

  for api in apis:

    code += '\n'
    if api.name in cond:
      code += '#if %s\n' % cond[api.name]

    for function in api.functions:

      if getattr(function,'regalOnly',False)==True:
        continue

      if not function.needsContext:
        continue

      name   = function.name
      params = paramsDefaultCode(function.parameters, True)
      callParams = paramsNameCode(function.parameters)
      rType  = typeCode(function.ret.type)
      category  = getattr(function, 'category', None)
      version   = getattr(function, 'version', None)

      if category:
        category = category.replace('_DEPRECATED', '')
      elif version:
        category = version.replace('.', '_')
        category = 'GL_VERSION_' + category

      # Close prev category block.
      if categoryPrev and not (category == categoryPrev):
        code += '\n'

      # Begin new category block.
      if category and not (category == categoryPrev):
        code += '// %s\n\n' % category

      categoryPrev = category

      code += 'static %sREGAL_CALL %s%s(%s) \n{\n' % (rType, 'statistics_', name, params)
      code += '  RegalContext *_context = REGAL_GET_CONTEXT();\n'
      code += '  RegalAssert(_context);\n'
      code += '\n'
      code += '  RegalAssert(_context->statistics);\n'
      code += '  Statistics &statistics = *_context->statistics;\n'
      code += '  statistics.%s++;\n'%(name)
      code += '\n'

      # Extension

      for i in api.extensions:
        if name in i.functions:
          code += '  statistics.%s++;\n'%(i.name.lower())
        code += '\n'

      # glEnable

      if name=='glEnable':
        code += '  switch (cap)\n'
        code += '  {\n'
        for i in api.enums:
          if i.name=='defines':
            for j in i.enumerantsByName:
              if getattr(j,'enableCap',False) == True:
                code += '    case %-40s %-60s break;\n'%(j.name+':','statistics.enable_%s++;'%j.name)
        code += '    default: break;\n'
        code += '  }\n\n'

      # glDisable

      if name=='glDisable':
        code += '  switch (cap)\n'
        code += '  {\n'
        for i in api.enums:
          if i.name=='defines':
            for j in i.enumerantsByName:
              if getattr(j,'enableCap',False) == True:
                code += '    case %-40s %-60s break;\n'%(j.name+':','statistics.disable_%s++;'%j.name)
        code += '    default: break;\n'
        code += '  }\n\n'

      if function.needsContext:
        code += '  DispatchTableGL *_next = _context->dispatcher.statistics.next();\n'
      else:
        code += '  DispatchTableGlobal *_next = dispatcherGlobal.statistics.next();\n'
      code += '  RegalAssert(_next);\n'

      code += '  '
      if not typeIsVoid(rType):
        code += '%s ret = ' % rType
      code += '_next->call(&_next->%s)(%s);\n' % ( name, callParams )
      if not typeIsVoid(rType):
        code += '  return ret;\n'
      code += '}\n\n'

    if api.name in cond:
      code += '#endif // %s\n' % cond[api.name]
    code += '\n'

  # Close pending if block.
  if categoryPrev:
    code += '\n'

  return code

def generateDispatchStatistics(apis, args):

  funcDefine     = apiStatisticsFuncDefineCode( apis, args )
  funcInit       = apiDispatchFuncInitCode( apis, args, 'statistics' )

  # Output

  substitute = {}

  substitute['LICENSE']         = args.license
  substitute['AUTOGENERATED']   = args.generated
  substitute['COPYRIGHT']       = args.copyright
  substitute['DISPATCH_NAME']   = 'Statistics'
  substitute['LOCAL_INCLUDE']   = '#include "RegalStatistics.h"'
  substitute['LOCAL_CODE']      = ''
  substitute['API_DISPATCH_FUNC_DEFINE']      = funcDefine
  substitute['API_DISPATCH_FUNC_INIT']        = funcInit
  substitute['API_DISPATCH_GLOBAL_FUNC_INIT'] = ''
  substitute['IFDEF'] = '#if REGAL_STATISTICS\n\n'
  substitute['ENDIF'] = '#endif\n'

  outputCode( '%s/RegalDispatchStatistics.cpp' % args.srcdir, dispatchSourceTemplate.substitute(substitute))

